%% Author: Administrator
%% Created: 2009-4-1
%% Description: TODO: Add description to gdal_band
-module(spectrometer_server).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([start/1, stop/0, init/1]).
-export([split_light/1]).
-export([foo/1, fb/0, memory_test/1]).

%%
%% API Functions
%%
start(ExtPrg) ->
    spawn(?MODULE, init, [ExtPrg]).

stop() ->
    ?MODULE ! {stop}.

fb() ->
    {ok, Bin} = file:read_file("01.jpg"),
    split_light(Bin).

memory_test(N) ->
    {ok, File} = file:open("port_time.log", write),
    io:format(File, "handle_time\t microseconds~n", []),
    memory_test(File, N).
memory_test(File, 0) ->
    file:close(File),
    ok;
memory_test(File, N) ->
    {ok, Bin} = file:read_file("01.jpg"),
    {Time, _} = timer:tc(?MODULE, split_light,[Bin]),
    if 
        (N rem 6) == 0 ->
            io:format(File, "~p\t~p~n", [time(), Time]);
        true ->
            ok
    end,
    timer:sleep(5*1000),
    memory_test(File, N-1).
    
    
split_light(Bin) ->
    Res = call_port({light_split, Bin}),
    [{Xsize1, Ysize1, Bin1},{Xsize1, Ysize1, Bin2},{Xsize1, Ysize1, Bin3}] = Res
%    ,io:format("xsize: ~p, ysize: ~p, bin1_size: ~p, bin2_size: ~p, bin3_size: ~p~n", 
%        [Xsize1,Ysize1, size(Bin1), size(Bin2), size(Bin3)])
    .

foo(X) ->
    call_port({foo, X}).

%%
%% Local Functions
%%
call_port(Msg) ->
    ?MODULE ! {call, self(), Msg},
    receive
        {?MODULE, Result} ->
            Result
    end.

init(ExtPrg) ->
    register(?MODULE, self()),
    process_flag(trap_exit, true),
    Port = open_port({spawn, ExtPrg}, [{packet,4}, binary]),
    loop(Port).

loop(Port) ->
    receive
        {call, Caller, Msg} ->
            Port ! {self(), {command, term_to_binary(Msg)}},
            receive
                {Port, {data, Data}} ->
                    Caller ! {?MODULE, binary_to_term(Data)}
            end,
            loop(Port);
        {stop} ->
            Port ! {self(), close},
            receive
                {Port, closed} ->
                    exit(normal)
            end;
        {'EXIT', Port, Reason} ->
            io:format("exit reason: ~p~n", [Reason]),
            exit(port_terminated)
    end.

